﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Security.Cryptography.X509Certificates;


namespace libmvdkbot
{
    public class WebEngine
    {
        private const String InitURL = "https://smartweb.keralamvd.gov.in/kmvdnew/services/registration/tempreg.php";
        private const String requestUrl = "http://smartweb.keralamvd.gov.in/kmvdnew/services/registration/tempreg_details.php?tregfield={0}&Submit=Get";
        private const String PostRequestURL = "https://smartweb.keralamvd.gov.in/kmvdnew/services/registration/tempreg_details.php";
        private const String OfficeStart = "Office:\r\n            <font color=darkgreen>";
        private const String OfficeEnd = "</font>";
        private const String OwnerNameStart = "OwnerName</span></div>\r\n              </div></td>\r\n              <td width=\"224\" bgcolor=\"#f4f4f4\" class=\"style1\" align=\"left\">\r\n                <div align=\"left\">&nbsp;&nbsp;";
        private const String OwnerNameEnd = "                </div></td><td width=\"10\"";
        private const String PAddressStart = "Permanent Address</span></div></td>\r\n              <td rowspan=\"3\" bgcolor=\"#f4f4f4\" class=\"style1\" align=\"left\"><div align=\"left\">&nbsp;&nbsp;";
        private const String PAddressEnd = "</div></td>";
        private const String RTokenStart = "<input type=\"hidden\" name=\"r_token\" value=\"";
        private const String RTokenEnd = "\" />\r\n</form>";
        private static readonly String TempRegStart = "Temp Reg No</div></th>\r\n          <th width=\"183\" class=\"style1\"><div align=\"left\">&nbsp;&nbsp;<font color=darkgreen>";
        private static readonly String TempRegEnd = "</font></div></th>";
        private static readonly String TempAddressStart = "Temporary Address </span></div></td>\r\n              <td rowspan=\"3\" bgcolor=\"#F0EBF1\" class=\"style1\" align=\"left\"><div align=\"left\">&nbsp;&nbsp;\r\n                <font color= brown face=verdana size=1>";
        private static readonly String TempAddressEnd = "</font>";
        private static readonly String ValidUpToStart = "Valid upto </div>\r\n              </div></td>\r\n              <td bgcolor=\"#F0EBF1\" class=\"style1\">&nbsp;&nbsp;";
        private static readonly String ValidUptoEnd = "</td>";
        private static readonly String IssueDateStart = "Issue Date </span></div></td>\r\n              <td bgcolor=\"#f4f4f4\" class=\"style1\"><div align=\"left\">&nbsp;&nbsp;";
        private static readonly String IssueDateEnd = "</div></td>";
        private static readonly String MakersNameStart = "Maker's Name&nbsp;</div>\r\n              </div></td>\r\n              <td bgcolor=\"#F0EBF1\" class=\"style1\">&nbsp;&nbsp;";
        private static readonly String MakersNameEnd = "</td>\r\n            </tr>";
        private static readonly String MakersClassStart = "Maker's Classification</div></td>\r\n              <td bgcolor=\"#f4f4f4\" class=\"style1\">&nbsp;&nbsp;";
        private static readonly String MakersClassEnd = "</td>\r\n            </tr>";
        private static readonly String SeatInAllStart = "Seat in all&nbsp; </div>\r\n              </div></td>\r\n              <td bgcolor=\"#f4f4f4\" class=\"style1\">&nbsp;&nbsp;";
        private static readonly String SeatInAllEnd = "</td>\r\n            </tr>";

        private static CookieContainer _cookies = new CookieContainer();

        public static String GetScecretCode()
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                WebClient client = new WebClient();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InitURL);
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20120403211507 Firefox/14.0.1";

                X509Certificate cert = new X509Certificate(Properties.Resources.MVKDCert);
                request.ClientCertificates.Add(cert);

                request.AllowAutoRedirect = true;
                request.ContinueDelegate = new HttpContinueDelegate(new Action<int, WebHeaderCollection>(CheckHtppContinue));
                request.CookieContainer = _cookies;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                String data = reader.ReadToEnd();
                String token = GetTextBetween(data, RTokenStart, RTokenEnd);
                return token;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.Write(ex);
            }
            return String.Empty;
        }

        private static void CheckHtppContinue(int code, WebHeaderCollection header)
        {
            System.Diagnostics.Trace.Write("Check to Continue");
        }

        private static bool ValidateRemoteCertificate(object sender,
                                                        X509Certificate certificate,
                                                        X509Chain chain,
                                                        SslPolicyErrors policyErrors)
        {
            return true;
        }

        private static String GetPostResponse(String regionCode, String series, String number, String screctCode)
        {
            try
            {
                String tregfield = "KL-" + regionCode + "-" + series + "-TEMP-" + number;
                WebClient client = new WebClient();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PostRequestURL);
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20120403211507 Firefox/14.0.1";

                X509Certificate cert = new X509Certificate(Properties.Resources.MVKDCert);
                request.ClientCertificates.Add(cert);

                request.AllowAutoRedirect = true;
                request.ContinueDelegate = new HttpContinueDelegate(new Action<int, WebHeaderCollection>(CheckHtppContinue));
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = InitURL;
                request.CookieContainer = _cookies;

                String data = "r_token={0}&tregfield={1}&Submit=Get";
                data = String.Format(data, screctCode, Uri.EscapeDataString(tregfield));
                Byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data);
                request.ContentLength = buffer.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Close();               
                

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                String resp = reader.ReadToEnd();
                return resp;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.Write(ex);
                return String.Empty;
            }
        }

        public static TempRegInfo GetTempRegDetails(String regionCode, String series, String number, String screctCode)
        {
            TempRegInfo info = null;
            String response = GetPostResponse(regionCode, series, number, screctCode);
            if ((null != response) && (response.Contains(OfficeStart)))
            {
                info = new TempRegInfo();
                info.Office = GetTextBetween(response, OfficeStart, OfficeEnd);
                info.OwnerName = GetTextBetween(response, OwnerNameStart, OwnerNameEnd);
                info.PermenentAddress = GetTextBetween(response, PAddressStart, PAddressEnd);
                info.TemporaryAddress = GetTextBetween(response, TempAddressStart, TempAddressEnd);
                info.RegNumber = GetTextBetween(response, TempRegStart, TempRegEnd);
                info.ValidUpTo = GetTextBetween(response, ValidUpToStart, ValidUptoEnd);
                info.IssueDate  = GetTextBetween(response, IssueDateStart, IssueDateEnd);
                info.MakersName = GetTextBetween(response, MakersNameStart, MakersNameEnd);
                info.MakersClass = GetTextBetween(response, MakersClassStart, MakersClassEnd);
                info.SeatInAll = GetTextBetween(response, SeatInAllStart, SeatInAllEnd);
            }
            return info;
        }

        private static String GetTextBetween(String hay, String start, String end)
        {
            String result = String.Empty;
            Int32 pos = hay.IndexOf(start);
            if (0 <= pos)
            {
                Int32 pos2 = hay.IndexOf(end, (pos + start.Length));
                if ((pos + start.Length) <= pos2)
                {
                    result = hay.Substring(pos + start.Length, pos2 - (pos + start.Length));
                    result = result.Trim ("\r\n\t ".ToCharArray ());
                }
            }
            return result;
        }
    }
}
